<template>
  <div class="user-auth-page">

    <div class="login-auth-box">
      
      <!-- 顶部背景色 -->
      <tab-back :tabIndex="tabIndex"/>

      <div class="login-auth-tab-list">
        <div class="tab-item" :class="{'tab-item-select': tabIndex == 0}" @click="changeTabIndex(0)">密码登录</div>
        <div class="tab-item" :class="{'tab-item-select': tabIndex == 1}" @click="changeTabIndex(1)">验证码登录</div>
      </div>

      <!-- 登录 -->
      <div class="auth-group-input">
        <!-- 邮箱 -->
        <div class="input-box">
          <div class="input-title">邮箱</div>
          <el-autocomplete 
            type="email" 
            v-model="email" 
            placeholder="输入邮箱" 
            clearable 
            :fetch-suggestions="queryEamil"
            @blur="regEmail()" 
            @input="regEmail()"/>
        </div>

        <div class="input-group">

          <!-- 密码 -->
          <div class="input-box" :class="{'input-slide-down':tabIndex == 0 && initOK, 'input-slide-up':tabIndex == 1 && initOK}">
            <div class="input-title">密码</div>
            <el-input 
              id="password"
              v-model="password" 
              placeholder="输入密码" 
              show-password 
              clearable></el-input>
          </div>

          <!-- 验证码 -->
          <div class="input-box" :class="{'input-slide-down':tabIndex == 0 && initOK, 'input-slide-up':tabIndex == 1 && initOK}">
            <div class="input-title">验证码</div>
            <el-input :disabled="!regEmailSuccess" v-model="smsCode" maxlength="4" placeholder="输入验证码">
              <el-button 
                :disabled="!regEmailSuccess || getCodeBtnCountDown" 
                slot="suffix" 
                type="primary" 
                size="mini" 
                plain 
                @click="getSmsCode"
                >{{getCodeBtnText}}</el-button>
            </el-input>
          </div>
        </div>
      </div>

      <!-- 注册、登录按钮 -->
      <div class="auth-group-register login-btn">
        <el-button type="primary" @click="login">立即登录</el-button>

        <span class="change-type">
          <nuxt-link style="color : #409EFF" to="/userRegister">免费注册</nuxt-link>
        </span>
      </div>
    </div>
  </div>
</template>

<script>
import Api from "@/utils/api.js";
import Avatar from '@/components/Avatar.vue'
import CC from '@/utils/cc.js'
import TabBack from './components/tabBack.vue'
let interval;

export default {

  head () {
    return {
      title: `登录`,
      meta:[
        // 阻止搜索引擎编入索引
        { name:'robots',content: 'noindex'}
      ],
      script: [
        // 彩带动画
        { src: '/js/ribbon.js', body: true},
      ]
    }
  },  

  components:{
    Avatar,
    TabBack
  },

  data(){
    return{
      initOK: false,
      tabIndex: 0,
      email:'',
      password:'',
      smsCode:'',

      regEmailSuccess: false,

      getCodeBtnCountDown: false,
      getCodeBtnText:"立即获取",

      emailAllEnd:[
        {value : "@qq.com"},
        {value : "@163.com"},
        {value : "@sina.com"},
        {value : "@sina.cn"},
        {value : "@sohu.com"},
        {value : "@126.com"},
        {value : "@139.com"},
        {value : "@189.cn"},
        {value : "@outlook.com"},
        {value : "@hotmail.com"},
        {value : "@foxmail.com"},
        {value : "@21cn.com"},
        {value : "@aliyun.com"},
        {value : "@vip.163.com"},
        {value : "@vip.126.com"},
        {value : "@188.com"},
        {value : "@live.cn"},
        {value : "@gmail.com"},
        {value : "@yahoo.com"},
        {value : "@yeah.com"}
      ],

      // 获取登录前页面地址
      refUrl: ''
    }
  },

  mounted() {
    this.$nextTick(() => {
      this.refUrl = this.$route.query.ref
    })
  },

  methods:{
    changeTabIndex(value){
      if(value != this.tabIndex){
        this.tabIndex = value;
        this.initOK = true;
      }
    },

    // 邮箱推荐
    queryEamil(queryString, callback) {
      let emailLeft="";
      let emailRight="";
      if(queryString.indexOf("@")>0){
        // 邮箱@左边的内容
        emailLeft = queryString.substring(0, queryString.indexOf("@"));
        // 邮箱@右边的内容
        emailRight = queryString.substring(queryString.indexOf("@"));
      }else{
        emailLeft = queryString;
      }

      // 调用 callback 返回建议列表的数据
      if(queryString){
        var results = JSON.parse(JSON.stringify(this.emailAllEnd))
        // 补充邮箱输入的内容
        results = results.map( item => {
          item.value = emailLeft + item.value
          return item
        })

        // 过滤符合格式的邮箱地址
        results = results.filter(item => (item.value.indexOf(emailRight) > 0 || !emailRight) && queryString != item.value )
        callback(results);
      }else{
        // 返回空选项
        callback([]);
      }     
    },

    //邮箱错误验证
    regEmail(){
      const reg = /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/;
      this.regEmailSuccess = reg.test(this.email)
    },

    // 登录
    login(){
      //邮箱错误验证
      this.regEmail()
      if(!this.regEmailSuccess){
        this.$message.warning("请输入正确的邮箱地址");
        return
      }
      
      // 登录url
      let loginUrl= Api.USER_LOGIN
      let loginParams = this.tabIndex == 0 ? {
        type: 0,
        email: this.email,
        password : CC.encryptPassword(this.password)
      } : {
        type: 1,
        email: this.email,
        code : this.smsCode
      }
      
      // 登录
      this.$axios.post(loginUrl, loginParams).then( res =>{
        if(this.refUrl){
          window.location.replace(this.refUrl)
        }else{
          window.location.replace("/")
        }
      }).catch(res =>{
        // 提示失败
        this.$message.warning(res.message);
      })
    },

    // 获取登录验证码
    getSmsCode(){
      this.getCodeBtnCountDown = true
      this.$axios.post(Api.SMS_LOGIN_CODE, {email: this.email}).then( _ =>{
        // 提示查收
        this.$message.success("已发送验证码，请查收！");
        // 验证码倒计时
        this.countDown(60)

      }).catch(res =>{
        // 初始化验证码获取按钮状态
        this.getCodeBtnCountDown = false
        // 提示失败
        this.$message.warning(res.message);
      })
    },

    // 验证码倒计时
    countDown(time){

      // 倒计时初始化
      clearInterval(this.interval)
      this.getCodeBtnText = time + "s"

      this.interval = setInterval(() => {
        if(time > 0){
          time --;
          this.getCodeBtnText = time + "s"
        }
        else{
          clearInterval(interval);
          this.getCodeBtnText = '重新获取';
          this.getCodeBtnCountDown = false;
        }
      }, 1000)
    },
  }
}
</script>

<style lang="less">
@import '@/assets/css/index.less';
.el-input, .el-autocomplete{
  flex: 1;
  
  .el-input__prefix, .el-input__suffix{
    .flex-center-center();
  }
}
</style>

<style lang="less" scoped>
@import './index.less';
</style>

<style lang="less">
@media screen and (max-width: 1023px) {
  
  // 邮箱、密码，验证码输入框
  .el-input, .el-input__inner{
    height: 35px;
    line-height:35px;
    font-size: 12px;
  }

  // 邮箱弹出框
  .el-autocomplete-suggestion li {
    font-size: 12px;
  }
}
</style>
